/*
 * @Author: hcluo
 * @Date: 2020-08-30 09:28:53
 * @LastEditors: hcluo
 * @LastEditTime: 2020-08-30 15:53:19
 * @Description:
 */
import React, { useState, useMemo, useRef } from 'react';
import useSize from 'ahooks/es/useSize';
export default function VirtualScrolling(props) {
  const ref = useRef();
  const size = useSize(ref);
  const tableInfo = useMemo(() => {
    const { columnNum, rowNum } = props;
    const { width, height } = size;
    let itemWidth = width / columnNum;
    let itemHeight = height / rowNum;
    let fontSize = Math.min(itemWidth, itemHeight);

    let allRowNum = Math.ceil(props.data.length / rowNum);

    let containerWidth = allRowNum * itemWidth;
    return {
      width, //可视区域宽度
      height, //可视区域高度
      columnNum, //可视区域数据列数
      rowNum, //可视区域数据行数

      itemWidth, //单个元素宽度
      itemHeight, //单个元素宽度
      fontSize, //单个元素宽度

      containerWidth, // 滚动条容器宽度
    };
  }, [props, size]);

  const [offset, setOffset] = useState(0);

  const children = useMemo(() => {
    let list = [...props.data];
    let res = list.length
      ? list.slice(offset * tableInfo.rowNum, (offset + tableInfo.columnNum) * tableInfo.rowNum)
      : undefined;

    if (!!res) {
      return res.map((v, index) => {
        return (
          <div
            style={{
              width: tableInfo.itemWidth + 'px',
              height: tableInfo.itemHeight + 'px',
              // fontSize: '0.5em',
            }}
            key={index}
          >
            {props.render(v, index)}
          </div>
        );
      });
    } else {
      return props.noDataTips || '暂无数据';
    }
  }, [offset, tableInfo, props]);

  return (
    <div
      onScroll={event => {
        var { scrollLeft } = event.target;
        setOffset(~~(scrollLeft / tableInfo.itemWidth));
      }}
      style={{
        width: '100%',
        height: '100%',
        overflowX: 'scroll',
        marginTop: '10px',
      }}
      ref={ref}
    >
      <div
        style={{
          height: tableInfo.height + 'px',
          width: tableInfo.containerWidth + 'px',
        }}
      >
        <div
          style={{
            height: tableInfo.height + 'px',
            width: tableInfo.width + 'px',
            position: 'absolute',
            alignContent: 'start',
            margin: '0px',
            display: 'flex',
            flexWrap: 'wrap',
            flexDirection: 'column',
            //   fontSize: tableInfo.fontSize,
          }}
        >
          {children}
        </div>
      </div>
    </div>
  );
}

VirtualScrolling.defaultProps = {
  columnNum: 3, // 可视区域内数据列数
  rowNum: 5, // 可视区域内数据行数
  data: [], //数据
  noDataTips: '暂无数据', //自定义暂无数据提示
};
